package com.example.demo.controller.common;

import com.example.demo.common.domain.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
public class CommonController {
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    // 设置固定的日期格式
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    // 将 yml 中的自定义配置注入到这里
    @Value("${gorit.file.root.path}")
    private String filePath;
    /**
     * 通用上传请求
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        // 得到格式化后的日期
        String format = sdf.format(new Date());
        // 获取上传的文件名称
        String fileName = file.getOriginalFilename();
        // 时间 和 日期拼接
        String newFileName = format + "_" + fileName;
        // 得到文件保存的位置以及新文件名
        File dest = new File(filePath + newFileName);

        try
        {
            // 上传的文件被保存了
            file.transferTo(dest);

            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", newFileName);
            log.info("上传成功，当前上传的文件保存在 {}",filePath + newFileName);
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

//    /**
//     * 同用下载请求
//     */
//    @GetMapping("/download")
//    public AjaxResult download(String fileName, HttpServletResponse response) {
//
//        try {
//            //读取文件
//            String path = filePath + fileName;
//            //创建文件对象
//            File file = new File(path);
//            //将文件以输入流的形式读取
//            FileInputStream fis = new FileInputStream(file);
//            //获取缓冲字符集
//            BufferedReader reader = new BufferedReader(new InputStreamReader(fis, StandardCharsets.UTF_8));
//            //涉资response响应头 等信息
//            response.reset();//垂直响应流
//            //设置响应类型是：流
//            response.setHeader("content-type", "application/octet-stream");
//            //设置响应内容位置，这里是以附件的形式响应给客户端
//            //这里需要通过URLEncoder进行编码，否则中文名称会乱码
//            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
//            //设置响应字符集
//            response.setCharacterEncoding("UTF-8");
//            //获取输出流对象
//            PrintWriter out = response.getWriter();
//            //从输入流读取数据，通过输出流响应给浏览器
//            String line;
//            while ((line = reader.readLine()) != null) {
//                out.write(line);
//            }
//            //响应结束，关闭流
//            fis.close();
//            out.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//            return AjaxResult.error("文件下载失败");
//        }
//        return AjaxResult.success("文件下载成功");
//    }


    /**
     * 同用下载请求
     */
    @GetMapping("/download")
    public AjaxResult download(String fileName, HttpServletResponse response) {

        try (FileInputStream fis = new FileInputStream(filePath + fileName);
             BufferedInputStream bis = new BufferedInputStream(fis);
             OutputStream os = response.getOutputStream()) {
            // 设置响应头
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + URLEncoder.encode(fileName, "UTF-8"));
            response.setContentType("application/octet-stream");
            // 将输入流写入响应输出流中
            byte[] buffer = new byte[1024];
            int len;
            while ((len = bis.read(buffer)) > 0) {
                os.write(buffer, 0, len);
            }
            os.flush();
            return AjaxResult.success("文件下载成功");
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("文件下载失败");
        }
    }

    @GetMapping("/downloadApk/{fileName}")
    public ResponseEntity<InputStreamResource> downloadFile(@PathVariable String fileName) throws IOException {
        // 从本地获取 apk 文件
        File file = new File(filePath + fileName);
        System.out.println("下载了" + filePath + fileName);
        // 构建 ResponseEntity，设置响应头和响应内容
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename="+fileName+".apk");
        headers.add(HttpHeaders.CONTENT_TYPE, "application/vnd.android.package-archive");
        headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(file.length()));
        InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(resource);
    }
}
